#!/usr/bin/env ruby
require 'json'

IGNORE = ['in', 'required']

# json['paths']['/repos/{owner}/{repo}']['patch']['parameters']
data = File.read('api.json')
json = JSON.parse(data)
json['paths'].each do |_, path|
  path.each do |_, method|
    next unless parameters = method['parameters']

    required = []
    properties = {}
    parameters.each_with_index do |parameter, i|
      next unless parameter['in'] == 'formData'

      name = parameter['name']
      required.push(name) if parameter['required']

      parameter.each do |k, v|
        next if IGNORE.include?(k)
        properties[name] ||= {}
        properties[name][k] = v
      end
      parameters[i] = nil
    end
    next if properties.empty?

    properties.each do |k, v|
      properties[k].delete('name')
    end
    body_parameter = {
      'in': 'body',
      'schema': {
        'type': 'object',
        'properties': properties
      }
    }
    body_parameter[:schema][:required] = required unless required.empty?
    parameters.push(body_parameter)
    parameters.compact!
  end
end

File.open('api.json', 'w') do |f|
  f.puts JSON.pretty_generate(json)
end

